package com.zijidelu.luframework.base.bizsig;

import cn.hutool.core.lang.func.Func1;
import cn.hutool.core.lang.func.LambdaUtil;
import com.zijidelu.luframework.base.model.DataModel;
import lombok.Builder;
import lombok.Getter;
import lombok.ToString;

import java.util.Objects;

/**
 * 合成键。
 * <p>
 * 业务签名构建信息。
 *
 * @author ZIJIDELU
 * @datetime 2024/9/2318:50
 */
@Getter
@ToString
public class FieldDescriptor<D extends DataModel> {
    /**
     * Key字段
     * <p>
     * 实体类的字段引用，实体的唯一键字段
     */
    private final Func1<D, ?> field;

    /**
     * Key字段名称
     * <p>
     * 用于查询器条件查询
     */
    private final String fieldName;

    /**
     * Key字段名称别名
     * <p>
     * 用于格式化输出
     */
    private final String fieldNameAlias;

    /**
     * 空字段样式
     */
    private final String nullStyle;

    /**
     * 字段样式
     */
    private final String fieldStyleFormat;

    @Builder
    public FieldDescriptor(final Func1<D, ?> field, final String fieldNameAlias) {
        Objects.requireNonNull(field, "CompositeKey field cannot be null during initialization");
        Objects.requireNonNull(fieldNameAlias, "CompositeKey fieldNameAlias cannot be null during initialization");

        this.field = field;
        this.fieldNameAlias = fieldNameAlias;
        this.fieldName = LambdaUtil.getFieldName(field);
        this.nullStyle = fieldName + "(" + fieldNameAlias + ")=null";
        this.fieldStyleFormat = fieldName + "(" + fieldNameAlias + ")=";
    }

    public static <D extends DataModel> FieldDescriptor<D> of(final Func1<D, ?> field, final String fieldNameAlias) {
        return new FieldDescriptor<>(field, fieldNameAlias);
    }

    /**
     * 计算输出样式
     *
     * @param fieldValue 字段值
     * @return 样式
     */
    public String calcStyle(Object fieldValue) {
        return fieldStyleFormat + fieldValue.toString();
    }

}
